import React, { useState, useEffect } from 'react';
import { Carousel } from 'antd';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import { ApiService } from '../services/api';
import './Hero.css';

const Hero = () => {
  const [banners, setBanners] = useState([]);
  const [error, setError] = useState(null);
  const [isInitialized, setIsInitialized] = useState(false);
  const carouselRef = React.useRef();

  // 获取轮播图数据
  useEffect(() => {
    if (isInitialized) return;
    
    const fetchBanners = async () => {
      try {
        
        const response = await ApiService.getTopBannerList();
        
        if (response && response.code === '0000' && response.data) {
          // 按serNum排序
          const sortedBanners = response.data.sort((a, b) => a.serNum - b.serNum);
          setBanners(sortedBanners);
        } else {
          setError('获取轮播图数据失败: ' + (response?.msg || '未知错误'));
          console.error('接口返回错误:', response);
        }
        
      } catch (err) {
        console.error('获取轮播图失败:', err);
        setError('网络请求失败: ' + err.message);
      } finally {
        setIsInitialized(true);
      }
    };

    fetchBanners();
  }, [isInitialized]);

  // 手动切换
  const goToPrevious = () => {
    carouselRef.current?.prev();
  };

  const goToNext = () => {
    carouselRef.current?.next();
  };

  if (error && banners.length === 0) {
    return (
      <div className="hero-banner error">
        <div className="error-message">
          <p>{error}</p>
        </div>
      </div>
    );
  }

  return (
    <section className="hero-banner">
      <div className="banner-container">
        <Carousel
          ref={carouselRef}
          autoplay
          autoplaySpeed={5000}
          dots={banners.length > 1}
          arrows={false}
          effect="fade"
        >
          {banners.map((banner) => (
            <div key={banner.serNum} className="banner-slide">
              <div
                className="banner-image"
                style={{
                  backgroundImage: `url(${banner.picUrl})`,
                }}
              />
            </div>
          ))}
        </Carousel>

        {/* 自定义导航箭头 */}
        {banners.length > 1 && (
          <>
            <button className="banner-nav prev" onClick={goToPrevious}>
              <LeftOutlined />
            </button>
            <button className="banner-nav next" onClick={goToNext}>
              <RightOutlined />
            </button>
          </>
        )}
      </div>
    </section>
  );
};

export default Hero;
